package com.sundablog.service.impl.systemsetup.basicsetup.shortmessage;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sundablog.mapper.ShortMessageMapper;
import com.sundablog.pojo.ShortMessage;
import com.sundablog.pojo.ShortMessageExample;
import com.sundablog.service.systemsetup.basicsetup.shortmessage.ShortMessageService;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

/**
 * 短信接口实现类
 * 
 * @ClassName: ShortMessageServiceImpl
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: 哒哒
 * @date: 2018年1月2日 下午3:16:20
 * 
 * @Copyright: 2018 www.sundablog.com Inc. All rights reserved.
 */
@Service
public class ShortMessageServiceImpl implements ShortMessageService {

	@Autowired
	private ShortMessageMapper shortMessageMapper;

	/**
	 * 添加短信接口数据 Title: addShortMessage Description:
	 * 
	 * @param shortMessage
	 * @return
	 * @see com.sundablog.service.systemsetup.basicsetup.shortmessage.ShortMessageService#addShortMessage(com.sundablog.pojo.ShortMessage)
	 */
	@Override
	public int addShortMessage(ShortMessage shortMessage) {
		int i = shortMessageMapper.insert(shortMessage);
		return i;
	}

	/**
	 * 修改短信接口数据 Title: updataShortMessage Description:
	 * 
	 * @param shortMessage
	 * @return
	 * @see com.sundablog.service.systemsetup.basicsetup.shortmessage.ShortMessageService#updataShortMessage(com.sundablog.pojo.ShortMessage)
	 */
	@Override
	public int updataShortMessage(ShortMessage shortMessage) {
		int i = shortMessageMapper.updateByPrimaryKey(shortMessage);
		return i;
	}

	/**
	 * 获取一条短信接口数据（注意就一条） Title: getShortMessage Description:
	 * 
	 * @return
	 * @see com.sundablog.service.systemsetup.basicsetup.shortmessage.ShortMessageService#getShortMessage()
	 */
	@Override
	public ShortMessage getShortMessage() {
		ShortMessageExample example = new ShortMessageExample();
		List<ShortMessage> list = shortMessageMapper.selectByExample(example);
		return list.get(0);
	}

	/**
	 * 测试短信发送 Title: testShortMessage Description:
	 * 
	 * @param type
	 * @param phone
	 * @param content
	 * @return
	 * @see com.sundablog.service.systemsetup.basicsetup.shortmessage.ShortMessageService#testShortMessage(int,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public int sendShortMessage(String phone, String content) {
		ShortMessage shortMessage = getShortMessage();
		if (shortMessage.getType() == 1) {
			try {
				 int i = sendAliyun(shortMessage, content, content);
				 return i;
			} catch (Exception e) {
				//进入Exception 默认是发送失败
				e.printStackTrace();
				return 0;
			}
		} else {
			int i = sendChanzor(shortMessage, phone, content);
			return i;
		}
	}
	
	/**
	 * 畅卓短信发送
	 * @Title: sendChanzor   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param shortMessage
	 * @param: @param phone
	 * @param: @param content
	 * @param: @return      
	 * @return: int      
	 * @throws
	 */
	public int sendChanzor(ShortMessage shortMessage, String phone, String content) {
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("account", shortMessage.getKeyid());
		paramMap.put("password", DigestUtil.md5Hex(shortMessage.getSecret()).toUpperCase());
		paramMap.put("mobile", phone);
		paramMap.put("content", content + "【" + shortMessage.getAutograph() + "】");
		String result = HttpUtil.post("http://api.chanzor.com/send", paramMap);
		System.err.println(result);
		JSON json = JSONUtil.parse(result);
		int status = (int) json.getByExp("status");
		if (status == 0) {
			return 1;
		} else {
			return 0;
		}
	}

	/**
	 * 阿里云验证码发送
	 * @Title: sendAliyun   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param shortMessage
	 * @param: @param phone
	 * @param: @param content
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: int      
	 * @throws
	 */
	public int sendAliyun(ShortMessage shortMessage, String phone, String content) throws Exception {
		// 产品名称:云通信短信API产品,开发者无需替换
		String product = "Dysmsapi";
		// 产品域名,开发者无需替换
		String domain = "dysmsapi.aliyuncs.com";

		// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
		String accessKeyId = shortMessage.getKeyid();
		String accessKeySecret = shortMessage.getSecret();
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");

		// 初始化acsClient,暂不支持region化
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		IAcsClient acsClient = new DefaultAcsClient(profile);

		// 组装请求对象-具体描述见控制台-文档部分内容
		SendSmsRequest request = new SendSmsRequest();
		// 使用post提交
		request.setMethod(MethodType.POST);
		// 必填:待发送手机号
		request.setPhoneNumbers(phone);
		// 必填:短信签名-可在短信控制台中找到
		request.setSignName(shortMessage.getAutograph());
		// 必填:短信模板-可在短信控制台中找到
		request.setTemplateCode(content);
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		request.setTemplateParam("{\"code\":\"1234\"}");
		// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者

		// hint 此处可能会抛出异常，注意catch
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

		if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
			System.err.println(sendSmsResponse);
			return 1;
		} else {
			return 0;
		}

	}

}
